#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <lcthw/dbg.h>
#include <lcthw/mystring.h>
//   implement
size_t mystrlen(const char *s)
{
    size_t len=0;
    while( *(s+len) != '\0' )
        len++;
    return len;
}
char* mystrcpy(char *dest, const char *src)
{
    size_t i=0;
    while(*(src+i) != '\0'){
        *(dest+i) = *(src+i);
        i++;
    }
    *(dest+i) = '\0';
    return dest;
}

char* mystrncpy(char *dest, const char *src, size_t n)
{
    size_t i=0;
    while(*(src+i) != '\0' && i<n){
        *(dest+i) = *(src+i);
        i++;
    }
    *(dest+i) = '\0';
    return dest;
}
char *mystrcat(char *dest, const char *src)
{
    size_t dest_len = mystrlen(dest);
    size_t i=0;
    while(*(src+i) != '\0'){
        *(dest+dest_len+i) = *(src+i);
        i++;
    }
    *(dest+dest_len+i) = '\0';

    return dest;
}

char *mystrncat(char *dest, const char *src, size_t n){
    size_t dest_len = mystrlen(dest);
    size_t i=0;
    while(*(src+i) != '\0' && i<n){
        *(dest+dest_len+i) = *(src+i);
        i++;
    }
    *(dest+dest_len+i) = '\0';
    return dest;
}

int mystrcmp(const char *s1, const char *s2)
{
    while(*s1 == *s2 && *s1!='\0')
    {
        s1++;
        s2++;
    }
    return (*s1 - *s2);
}
int mystrncmp(const char *s1, const char *s2, size_t n)
{
    // --n是先减后判断，n++是先判断完再减
    while( n && *s1 == *s2 && *s1!='\0' && --n)
    {
        s1++;
        s2++;
    }
    return (*s1 - *s2);
}
void *mymemset(void *s, int c, size_t n) {
// 由于按字节存放，因此c 只能在（0~255）
    char*tmp_s = (char*)s;
    unsigned char tmp_c = (unsigned char)c;
    while (n--)
    {
        *(tmp_s++) = tmp_c;
    }
    return s;
}
void *mymemcpy(void *dst, const void *src, size_t n) {
    char*dst_tmp = (char*)dst;
    char*src_tmp = (char*)src;
        while(n--)
        {
            *dst_tmp = *src_tmp;
            dst_tmp++;
            src_tmp++;
        }   
    return dst;
}
void *mymemmove(void *dst, const void *src, size_t n)
{
    char*dst_tmp = (char*)dst;
    char*src_tmp = (char*)src;
    if(dst<src){ //顺序
        while(n--)
        {
            *dst_tmp = *src_tmp;
            dst_tmp++;
            src_tmp++;
        }
    }

    else {  // 倒序
         while(n--)
            *(dst_tmp+n) = *(src_tmp+n);
    }  
    return dst;  
}

int mymemcmp(const void *s1, const void *s2, size_t n){
    // --n是先减后判断，n++是先判断完再减
    char*s1_tmp = (char*)s1;
    char*s2_tmp = (char*)s2;
    while(n && *s1_tmp == *s2_tmp && --n)
    {
        s1_tmp++;
        s2_tmp++;
    }
    return (*s1_tmp - *s2_tmp);
}